package bar.dark.lee.manager.card;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.manager.money.BankMoneyActivitiy;

public class CheckCardActivity extends SuperActivity implements OnClickListener
{
/////////////////////////////////////////////////////////////////
///////////////////		위젯 멤버 변수		/////////////////////
/////////////////////////////////////////////////////////////////
	
	public static final String CHECKCARD_DATA = "checkCard_data";
	
	private Button mBtnAdd;
	private ListView mListCheckCard;
	private View buttonView;
	
/////////////////////////////////////////////////////////////////
///////////////////		일반 멤버 변수		/////////////////////
/////////////////////////////////////////////////////////////////

	private ArrayList<CheckCardData> mArrayCheckCard;
	
	private View resultView;
	
	// 그 외
	private DBSQLite dbSql;
	
	
/////////////////////////////////////////////////////////////////
///////////////////		오버라이딩 메소드		/////////////////////
/////////////////////////////////////////////////////////////////

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setting_checkcard_activity);
		
		dbSql = DBSQLite.getInstance(this);
		
		if (getIntent().getBooleanExtra(BankMoneyActivitiy.LINK_CARD, false))
		{
			setGoneTipButton();
			setTitle("연결 카드 목록");
		}
		else
		{
			setGoneTitle();
		}
		
		initVariable();
		initWidget();
		initListener();
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		new ShowDialog().execute(0);
	}
	
	/**
	 * 데이터를 셋팅한다.
	 */
	private void setdata()
	{
		getCheckCardData();
		
		for (int i=0; i<mArrayCheckCard.size(); i++) 
		{
			getBankBookData(i, mArrayCheckCard.get(i).getBanklink());
		}
	}
	
	@Override
	public void onClick(View v) {
		if (v == mBtnAdd) {
			Intent intent = new Intent(this, CheckCardAddActivity.class);
			startActivityForResult(intent, 0);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}
	
/////////////////////////////////////////////////////////////////
///////////////////			일반 메소드		/////////////////////
/////////////////////////////////////////////////////////////////

	/**
	* 위젯 초기화
	*/
	private void initWidget() {
		mBtnAdd = (Button)findViewById(R.id.SETTING_CHECKCARD_btnAdd);
		mListCheckCard = (ListView)findViewById(R.id.SETTING_CHECKCARD_list);
		buttonView = findViewById(R.id.checkCardButtonView);
		
		resultView = getLayoutInflater().inflate(R.layout.view_no_result, null);
	}
	
	/**
	* 멤버 변수 초기화
	*/
	private void initVariable() 
	{
		mArrayCheckCard = new ArrayList<CheckCardData>();
	}
	
	/**
	* 리스너 초기화
	*/
	private void initListener() {
		mBtnAdd.setOnClickListener(this);
	}

	/**
	 * 체크카드 데이터 가져온다
	 */
	private void getCheckCardData() 
	{
		mArrayCheckCard = new ArrayList<CheckCardData>();
		
		String query = "";
		
		// 통장삭제에서 왔을경우 그 통장에 연결된 카드만 보여준다.
		if (getIntent().getBooleanExtra(BankMoneyActivitiy.LINK_CARD, false))
		{
//			query = "SELECT id, name, banklink FROM check_card WHERE banklink = " 
//				+ getIntent().getStringExtra(BankMoneyActivitiy.CARD_ID) + ";";
			
			query = "SELECT id, name, banklink, count FROM ( " +
					"SELECT b.id id, b.name name, b.banklink banklink, d.count count " +
					"FROM check_card b, checkcard_detail d " +
					"WHERE b.id = d.linkid and d.count > 0 and " +
					"b.banklink = " +	getIntent().getStringExtra(BankMoneyActivitiy.CARD_ID) + " ORDER BY count) " +
					"UNION ALL " +
					"SELECT id, name, banklink, count FROM ( " +
					"SELECT b.id id, b.name name, b.banklink banklink, d.count count " +
					"FROM check_card b, checkcard_detail d " +
					"WHERE b.id = d.linkid and d.count < 1 and " +
					"b.banklink = " +	getIntent().getStringExtra(BankMoneyActivitiy.CARD_ID) + " ORDER BY count);";
			
			buttonView.setVisibility(View.GONE);
		}
		else
		{
//			query = "SELECT id, name, banklink FROM check_card;";
			
			query = "SELECT id, name, banklink, count FROM ( " +
					"SELECT b.id id, b.name name, b.banklink banklink, d.count count " +
					"FROM check_card b, checkcard_detail d " +
					"WHERE b.id = d.linkid and d.count > 0 ORDER BY d.count) " +
					"UNION ALL " +
					"SELECT id, name, banklink, count FROM ( " +
					"SELECT b.id id, b.name name, b.banklink banklink, d.count count " +
					"FROM check_card b, checkcard_detail d " +
					"WHERE b.id = d.linkid and d.count < 1 ORDER BY d.count);";
			
			buttonView.setVisibility(View.VISIBLE);
		}
		
		dbSql.selectMapTile(this, query, new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				c.moveToFirst();
				
				int idIndex = c.getColumnIndex("id");
				int nameIndex = c.getColumnIndex("name");
				int banklinkIndex = c.getColumnIndex("banklink");
				int countIndex = c.getColumnIndex("count");
				
				for (int i = 0; i < count; i++)
				{
					CheckCardData data = new CheckCardData();
					data.setId(c.getInt(idIndex) + "");
					data.setName(c.getString(nameIndex));
					data.setBanklink(c.getInt(banklinkIndex)+"");
					data.setOrder(c.getInt(countIndex)+"");
					mArrayCheckCard.add(data);
					c.moveToNext();
				}
			}
		});
	}
	
	/**
	 * 통장 데이터 가져온다
	 */
	private void getBankBookData(final int index, String id) {
		
		dbSql.selectMapTile(this, "SELECT name, money FROM bankbook" +
				" WHERE id = " + id + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				c.moveToFirst();
				int moneyIndex = c.getColumnIndex("money");
				int nameIndex = c.getColumnIndex("name");
				mArrayCheckCard.get(index).setMoney(c.getString(moneyIndex));
				mArrayCheckCard.get(index).setLinkName(c.getString(nameIndex));
			}
		});
	}
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3)
		{
			CheckCardData data  = mArrayCheckCard.get(position);
			
			Intent intent = new Intent(CheckCardActivity.this, CheckCardUpdataActivity.class);
			intent.putExtra(CHECKCARD_DATA, data);
			startActivityForResult(intent, 0);
		}
	};
	

/////////////////////////////////////////////////////////////////
///////////////////			내부 클래스		/////////////////////
/////////////////////////////////////////////////////////////////

	/**
	 * 체크카드 리스트 아답터
	 */
	private class CheckCardListAdapter extends ArrayAdapter<CheckCardData> {
    	private Context context;
    	private int textViewResourceId;
    	private ArrayList<CheckCardData> items;
    	private LayoutInflater inflater;
    	
		public CheckCardListAdapter(Context context, int textViewResourceId, ArrayList<CheckCardData> items) {
			super(context, textViewResourceId, items);
			this.context = context;
			this.textViewResourceId = textViewResourceId;
			this.items = items;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			if (view == null) {
				inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = inflater.inflate(R.layout.list_item_card, null);
			}
			
			CheckCardData data = items.get(position);
			if (data != null) {
				TextView textName = (TextView)view.findViewById(R.id.SETTING_CHECKCARD_LIST_textName);
				TextView textLink = (TextView) view.findViewById(R.id.SETTING_CHECKCARD_LIST_linkName);
				TextView textMoney = (TextView)view.findViewById(R.id.SETTING_CHECKCARD_LIST_textMoney);
				
				textName.setText(data.getName());
				textLink.setText(data.getLinkName());
				textMoney.setText(BDUtil.getWon(data.getMoney()) + shape);
			}
			return view;
		}
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(CheckCardActivity.this);
			dialog.setCancelable(false);
			dialog.setMessage("Loading...");
			dialog.show();
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0)
			{
				setdata();
				return 0;
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			dialog.dismiss();
			
			if (result == 0)
			{
				if (mListCheckCard.getFooterViewsCount() > 0)
				{
					mListCheckCard.removeFooterView(resultView);
				}
				
				if (mArrayCheckCard.size() < 1)
				{
					mListCheckCard.addFooterView(resultView);
					mListCheckCard.setFooterDividersEnabled(false);
					mListCheckCard.setOnItemClickListener(null);
				}
				else
				{
					mListCheckCard.setOnItemClickListener(onItemClickListener);
					mListCheckCard.setFooterDividersEnabled(true);
				}
				
				CheckCardListAdapter mAdapterCheckCard = new CheckCardListAdapter(
						CheckCardActivity.this, R.layout.list_item_card, mArrayCheckCard);
				mListCheckCard.setAdapter(mAdapterCheckCard);
				mAdapterCheckCard.notifyDataSetChanged();
			}
		}
	}

	@Override
	protected void tipButton()
	{
	}
}
